package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class WechatServiceImpl implements WechatService {

    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session";
    private static final String PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";

    @Value("${wechat.appid}")
    private String appid;
    @Value("${wechat.secret}")
    private String secret;

    @Override
    public String getOpenId(String code) {

        HashMap<String, Object> map = new HashMap<>();
        map.put("appid",appid);
        map.put("secret",secret);
        map.put("js_code",code);
        map.put("grant_type","authorization_code");

        String result = HttpUtil.get(REQUEST_URL, map);
        JSONObject parseObj = JSONUtil.parseObj(result);
        String openid = parseObj.getStr("openid");
        if (ObjectUtil.isEmpty(openid)){
            throw new BaseException("获取openId失败");
        }
        return openid;
    }

    @Override
    public String getPhone(String phoneCode) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("code",phoneCode);
        // 发送POST请求
        String result = HttpUtil.post(PHONE_URL+getAccessToken(), JSONUtil.toJsonStr(map));
        // 解析返回的JSON
        JSONObject parseObj = JSONUtil.parseObj(result);
        if (parseObj.getInt("errcode") != 0){
            throw new BaseException("获取手机号失败");
        }
        return parseObj.getJSONObject("phone_info").getStr("phoneNumber");
    }

    public String getAccessToken(){
        HashMap<String, Object> map = new HashMap<>();
        map.put("grant_type","client_credential");
        map.put("appid",appid);
        map.put("secret",secret);

        String result = HttpUtil.get(ACCESS_TOKEN_URL, map);
        JSONObject parseObj = JSONUtil.parseObj(result);
        String accessToken = parseObj.getStr("access_token");
        if (ObjectUtil.isEmpty(accessToken)){
            throw new BaseException("获取access_token失败");
        }
        return accessToken;
    }
}
